﻿namespace EFML_Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Windows.Forms;

    using Creek.UI.EFML;
    using Creek.UI.EFML.Base.JS;
    using Creek.UI.EFML.Base.JS.ScriptingTypes;
    using Creek.UI.EFML.Base.JS.ScriptingTypes.Console;
    using Creek.UI.Effects;

    using EFML_Runtime.Internal;

    using Microsoft.ClearScript;
    using Microsoft.ClearScript.Windows;
    using Microsoft.JScript;
    using Microsoft.VisualBasic;

    using Extensions = Creek.UI.EFML.Extensions;

    public class App
    {
        #region Fields

        public JScriptEngine Engine = new JScriptEngine();

        public Dictionary<string, Form> forms = new Dictionary<string, Form>();

        internal WindowsScriptEngine engine;

        private readonly Exeutable _exeutable = new Exeutable();

        #endregion

        #region Constructors and Destructors

        public App(string filename)
        {
            this._exeutable.Load(new FileStream(filename, FileMode.Open));

            string strings;
            if (this._exeutable.Strings.ContainsKey(CultureInfo.CurrentCulture.Name))
            {
                strings = this._exeutable.Strings[CultureInfo.CurrentCulture.Name];
            }
            else if (this._exeutable.Strings.ContainsKey(this._exeutable.MainLanguage))
            {
                strings = this._exeutable.Strings[this._exeutable.MainLanguage];
            }
            else
            {
                strings = "<strings></strings>";
            }

            this.InitJs();
            foreach (var s in this._exeutable.Sources)
            {
                if (s.Key.EndsWith(".window"))
                {
                    Form f = EfmlForm.Build(s.Value, this.Engine, strings);
                    f.Icon = new Icon(new MemoryStream(this._exeutable.Info.Icon));
                    this.forms.Add(s.Key, f);
                }
            }
            foreach (var component in this._exeutable.Components)
            {
                var app = new App(component);
                app.Start();
                foreach (var f in app.forms)
                {
                    this.forms.Add(f.Key, f.Value);
                }
            }
        }

        #endregion

        #region Public Methods and Operators

        public void Start()
        {
            Application.Run(this.forms[this._exeutable.MainForm]);
        }

        public void Stop()
        {
            Application.Exit();
        }

        #endregion

        #region Methods

        private void InitJs()
        {
           
        }

        #endregion
    }
}